/**
 * 导出场景布局文件, 支持全量导出 & 局部导出.
 * 
 * @author yanxuan.lc
 */
let Vector3 = HaloEngine.Three.Vector3;
let Quaternion = HaloEngine.Three.Quaternion;
let Euler = HaloEngine.Three.Euler;
let Object3D = HaloEngine.Three.Object3D;
let GLTFExporter = HaloEngine.ThreeExt.GLTFExporter;
let Hierarchy = HaloEngine.Utils.Hierarchy;

// 初始化上下文
let scene = Sandbox.defaults().SCENE_MANAGER.active;
let models = new Map(editor3d.modelList.map(curr => ([curr.uuid, curr.modelName])));

// [参数设置] 导出目标: SELECTED | ALL
let target = 'ALL';
let candidates = target === 'SELECTED' ? [scene.activeObject] : scene.children;

// 递归场景对象
let locators = [];
Hierarchy.forEach(candidates, object => {
  if (object.model) {
    locators.push({
      model: object.model,
      name: object.name,
      position: object.group.getWorldPosition(new Vector3()),
      rotation: new Euler().setFromQuaternion(object.group.getWorldQuaternion(new Quaternion())),
      scale: object.group.getWorldScale(new Vector3()),
    });
  }
});

// 遍历待导出 Locator, 创建场景布局
let root = new Object3D();
locators.forEach(loc => {
  if (!models.has(loc.model)) {
    console.log(`Cannot find model '${loc.model}''.`);
    return;
  }
  const curr = new Object3D();
  curr.name = `模型$$${models.get(loc.model)}$$${loc.name}`;
  curr.position.set(loc.position.x, loc.position.y, loc.position.z);
  curr.rotation.set(loc.rotation.x, loc.rotation.y, loc.rotation.z);
  curr.scale.set(loc.scale.x, loc.scale.y, loc.scale.z);
  root.add(curr);
});

// 导出 GLTF 布局文件
let exporter = new GLTFExporter();
exporter.parse(root, gltf => {
  const link = document.createElement('a');
  link.href = URL.createObjectURL(new Blob([JSON.stringify(gltf)], { type: 'text/plain' }));
  link.download = 'locator.gltf';
  link.click();
});